<template>
  <div class="master-detail-container">
    <!-- 主表（左边） -->
    <el-card class="master-table">
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>主表数据</span>
        </div>
      </template>

      <!-- 主表查询条件 -->
      <el-form :inline="true" :model="masterQuery" class="query-form">
        <el-form-item label="名称">
          <el-input v-model="masterQuery.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="masterQuery.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadMasterData">查询</el-button>
          <el-button @click="resetMasterQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 主表数据 -->
      <el-table
          :data="masterData"
          max-height="calc(100vh - 420px)"
          border
          highlight-current-row
          @current-change="handleMasterRowChange"
          v-loading="masterLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>

      <!-- 主表分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="masterQuery.pageNum"
            v-model:page-size="masterQuery.pageSize"
            :total="masterTotal"
            @current-change="loadMasterData"
            @size-change="loadMasterData"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 子表（右边） -->
    <el-card class="detail-table">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>子表数据</span>
          <span v-if="currentMasterRow" class="selection-hint">
            当前主表: {{ currentMasterRow.name }}
          </span>
        </div>
      </template>

      <!-- 子表查询条件 -->
      <el-form :inline="true" :model="detailQuery" class="query-form">
        <el-form-item label="产品名称">
          <el-input v-model="detailQuery.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="detailQuery.type" placeholder="请选择类型" clearable>
            <el-option label="类型A" value="A" />
            <el-option label="类型B" value="B" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="loadDetailData"
              :disabled="!currentMasterRow"
          >
            查询
          </el-button>
          <el-button @click="resetDetailQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 子表数据 -->
      <el-table
          :data="detailData"
          border
          v-loading="detailLoading"
          :disabled="!currentMasterRow"
          max-height="calc(100vh - 420px)"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="productName" label="产品名称" width="150" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="price" label="价格" width="120" align="right">
          <template #default="{ row }">
            {{ formatCurrency(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleDetailEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 子表分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="detailQuery.pageNum"
            v-model:page-size="detailQuery.pageSize"
            :total="detailTotal"
            :disabled="!currentMasterRow"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="loadDetailData"
            @size-change="loadDetailData"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { List, Document } from '@element-plus/icons-vue'

// 主表相关
interface MasterItem {
  id: number
  name: string
  code: string
  status: string
  createTime: string
}

const masterQuery = ref({
  name: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const masterData = ref<MasterItem[]>([])
const masterTotal = ref(0)
const masterLoading = ref(false)
const currentMasterRow = ref<MasterItem | null>(null)

// 子表相关
interface DetailItem {
  id: number
  productName: string
  type: string
  price: number
  stock: number
}

const detailQuery = ref({
  productName: '',
  type: '',
  pageNum: 1,
  pageSize: 10
})

const detailData = ref<DetailItem[]>([])
const detailTotal = ref(0)
const detailLoading = ref(false)

// 加载主表数据
const loadMasterData = async () => {
  masterLoading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData: MasterItem[] = Array.from({ length: 50 }, (_, i) => ({
      id: i + 1,
      name: `主表项目 ${i + 1}`,
      code: `CODE-${1000 + i}`,
      status: Math.random() > 0.3 ? '1' : '0',
      createTime: new Date(Date.now() - Math.random() * 1e10).toLocaleString()
    }))

    // 模拟过滤
    let filtered = mockData.filter(item =>
        (!masterQuery.value.name || item.name.includes(masterQuery.value.name)) &&
        (!masterQuery.value.status || item.status === masterQuery.value.status)
    )

    masterTotal.value = filtered.length
    const start = (masterQuery.value.pageNum - 1) * masterQuery.value.pageSize
    masterData.value = filtered.slice(start, start + masterQuery.value.pageSize)
  } finally {
    masterLoading.value = false
  }
}

// 加载子表数据
const loadDetailData = async () => {
  if (!currentMasterRow.value) return

  detailLoading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData: DetailItem[] = Array.from({ length: 30 }, (_, i) => ({
      id: i + 1,
      productName: `${currentMasterRow.value?.name} - 产品 ${i + 1}`,
      type: Math.random() > 0.5 ? 'A' : 'B',
      price: Math.round(Math.random() * 10000) / 100,
      stock: Math.floor(Math.random() * 1000)
    }))

    // 模拟过滤
    let filtered = mockData.filter(item =>
        (!detailQuery.value.productName || item.productName.includes(detailQuery.value.productName)) &&
        (!detailQuery.value.type || item.type === detailQuery.value.type)
    )

    detailTotal.value = filtered.length
    const start = (detailQuery.value.pageNum - 1) * detailQuery.value.pageSize
    detailData.value = filtered.slice(start, start + detailQuery.value.pageSize)
  } finally {
    detailLoading.value = false
  }
}

// 主表行选中变化
const handleMasterRowChange = (row: MasterItem | null) => {
  currentMasterRow.value = row
  if (row) {
    detailQuery.value.pageNum = 1 // 重置子表页码
    loadDetailData()
  } else {
    detailData.value = []
    detailTotal.value = 0
  }
}

// 重置查询条件
const resetMasterQuery = () => {
  masterQuery.value = {
    name: '',
    status: '',
    pageNum: 1,
    pageSize: 10
  }
  loadMasterData()
}

const resetDetailQuery = () => {
  detailQuery.value = {
    productName: '',
    type: '',
    pageNum: 1,
    pageSize: 10
  }
  loadDetailData()
}

// 辅助函数
const formatCurrency = (value: number) => {
  return '¥' + value.toFixed(2)
}

const handleDetailEdit = (row: DetailItem) => {
  console.log('编辑子表行:', row)
  // 实际项目中这里弹出编辑对话框
}

// 初始化加载主表数据
onMounted(() => {
  loadMasterData()
})
</script>

<style scoped>
.master-detail-container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.master-table {
  width: 45%;
  min-width: 500px;
}

.detail-table {
  flex: 1;
  min-width: 600px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selection-hint {
  margin-left: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.query-form {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 增强选中行的视觉效果 */
:deep(.el-table__row.current-row) {
  background-color: var(--el-color-primary-light-9);
}
</style>